#!/usr/bin/bash
set -e

# 获取安装版本
echo -n "install doris version(2.1.2): "
read version

download_path="https://apache-doris-releases.oss-accelerate.aliyuncs.com/apache-doris-${version}-bin-x64.tar.gz"
binary_name=`basename ${download_path}`

package_dir="/srv/package/"
install_dir="/srv/software/"
custom_env_file="/etc/profile.d/custom_env.sh"

# 创建存放目录，下载和安装
mkdir -p ${package_dir} ${install_dir}
wget ${download_path} -P ${package_dir}
tar xf ${package_dir}${binary_name} -C ${install_dir}
mv ${install_dir}apache-doris-${version}-bin-x64 ${install_dir}doris-${version}

# 添加环境变量
software_name=$(ls -l ${install_dir} |grep doris |grep ${version} |awk '{print $9}')
software_home=${install_dir}${software_name}
cat >> ${custom_env_file} <<-EOF
export DORIS_HOME=${software_home}
export PATH=\$DORIS_HOME/bin:\$PATH
EOF
source /etc/profile

# 修改配置文件
# 修改 be.conf 的 JAVA_HOME 路径
be_conf=${software_home}/be/conf/be.conf
sed -i "s|# JAVA_HOME.*|JAVA_HOME=$JAVA_HOME|" be_conf

# 配置启动脚本
cat > /usr/local/bin/doris-standalone-daemon.sh <<EOF
#!/bin/bash
source /etc/profile
if [ -z "\$DORIS_HOME" ]; then
    echo "Error: DORIS_HOME is not set."
    exit 1
fi

case \$1 in
"start")
    echo "===== doris \$1 ====="
    \${DORIS_HOME}/fe/bin/start_fe.sh --daemon
    \${DORIS_HOME}/be/bin/start_be.sh --daemon
;;
"stop")
    echo "===== doris \$1 ====="
    \${DORIS_HOME}/be/bin/stop_be.sh
    \${DORIS_HOME}/fe/bin/stop_fe.sh
;;
*)
    echo "Unknown command: $1"
    exit 1
;;
esac
EOF
chmod 755 /usr/local/bin/doris-standalone-daemon.sh


# 安装成功提示
echo "Successfully installed doris-standalone..."